package com.anlu.concurrent.ch2.future;

import com.anlu.concurrent.utils.SleepTools;

import javax.jws.soap.SOAPBinding;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <p>
 * Description: 演示future的使用
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/6 15:47
 */
public class UseFuture {
    private static class UseCallable implements Callable<Integer>{

        private int sum;

        @Override
        public Integer call() throws Exception {
            System.out.println("Callable子线程开始计算");
            Thread.sleep(2000);
            for (int i=0;i<5000;i++){
                sum = sum+i;
            }
            System.out.println("Callable子线程计算完成，结果="+sum);
            return sum;
        }
    }

    public static void main(String[] args)throws InterruptedException, ExecutionException {
        UseCallable callable = new UseCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start();
        System.out.println("主线程可以继续做其他事情");

        Random r = new Random();
        SleepTools.second(1);

        //随机决定是获得结果还是终止任务
        if(r.nextBoolean()){
            System.out.println("Get UseCallable result = "+futureTask.get());
        }else{
            System.out.println("中断计算");
            futureTask.cancel(true);
        }
    }
}
